#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/11 16:07
# @File    : canvas_app.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn

import tkinter as tk

import numpy as np
import pandas as pd
import ttkbootstrap as ttk
from ttkbootstrap.dialogs import Messagebox


class DraggableFrame(ttk.Frame):

    def __init__(self, master=None, **kwargs):

        super().__init__(master, **kwargs)
        self.master = master
        self.bind("<Button-1>", self.on_start_drag)
        self.bind("<Button-3>", self.popup) # 右键事件
        self.bind("<B1-Motion>", self.on_dragging)
        self.bind("<ButtonRelease-1>", self.on_stop_drag)
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)
        self._drag_data = {"x": 0, "y": 0}
        # 定义一个全局变量来跟踪鼠标是否正在标签上滑过
        self.is_hovering = False

    def on_start_drag(self, event):
        self._drag_data["x"] = event.x
        self._drag_data["y"] = event.y

    def on_enter(self, event):
        # 鼠标进入时改变背景色
        self.is_hovering = True
        print("鼠标进来了")

        # 安排一个回调函数在1秒后执行，以恢复背景色
        self.after(1000, self.on_leave)

    def on_leave(self, event=None):
        self.is_hovering = False
        # 鼠标离开时恢复背景色
        print("鼠标离开")

    def popup(self, event):
        # 创建一个弹出菜单
        popup_menu = tk.Menu(self, tearoff=0)
        popup_menu.add_command(label="信息", command=lambda: self.info())
        popup_menu.add_command(label="删除", command=lambda: self.delete())
        # 显示弹出菜单
        popup_menu.tk_popup(event.x_root, event.y_root)

    def info(self):
        info = {
            'class': self.winfo_class(),
            'id': self.winfo_id(),
            'name': self.winfo_name(),
            'parent': self.winfo_parent(),
            'x': self.winfo_x(),
            'y': self.winfo_y(),
            'width': self.winfo_width(),
            'height': self.winfo_height(),
            'config': self.config()  # 获取所有配置选项和它们的值
        }
        Messagebox.ok(info.__str__(), position=(500, 500))
        print(info)

    def delete(self):
        print("删除事件")
        self.destroy()

    def clear_all_widgets(self):
        print("删除当前frame下所有子组件")
        for widget in self.winfo_children():
            widget.destroy()

    def on_dragging(self, event):
        delta_x = event.x - self._drag_data["x"]
        delta_y = event.y - self._drag_data["y"]
        x = self.winfo_x() + delta_x
        y = self.winfo_y() + delta_y

        print("-------------------")
        parent_width = self.master.winfo_width()
        parent_height = self.master.winfo_height()
        current_frame_width = self.winfo_width()
        current_frame_height = self.winfo_height()
        print(f"current frame size ({current_frame_width},{current_frame_height})")
        print(f"parent Frame Width: {parent_width} pixels Height: {parent_height} pixels")
        # 最大不可 超出frame最大高度 最少暴漏出10个像素点
        x = x if parent_width > x else parent_width - 10
        y = y if parent_height > y else parent_height - 10
        x = -current_frame_width+10 if x <= -current_frame_width+10 else x
        y = -current_frame_height+10 if y <= -current_frame_height+10 else y
        print(f"move to ({x},{y})")

        self.place(x=x, y=y)

    def on_stop_drag(self, event):
        print("停止移动")
        pass  # 可以在这里添加停止拖动时的处理逻辑


class Body(ttk.Frame):

    def __init__(self, master=None, **kwargs):
        super().__init__(master, **kwargs)
        self.master = master
        self.pack(fill=ttk.BOTH, expand=ttk.YES)
        # 头部
        self.top = ttk.Frame(self, bootstyle="primary", height=50)
        self.top.pack(fill=ttk.X, side=ttk.TOP)
        # 内容
        self.div = ttk.Frame(self, bootstyle="warning")
        self.div.pack(fill=ttk.BOTH, expand=ttk.YES, side=ttk.TOP)
        # 底部
        self.bottom = ttk.Frame(self, bootstyle="light", height=20)
        self.bottom.pack(fill=ttk.X, side=ttk.TOP)

        # 内容扩展
        self.tab_control = ttk.Frame(self.div, bootstyle="secondary", width=50)
        self.tab_control.pack(fill=ttk.Y, side=ttk.LEFT)

        self.body = ttk.Panedwindow(self.div, orient='horizontal')
        self.body.pack(fill=ttk.BOTH, expand=ttk.YES, side=ttk.LEFT)

        self.sidebar = ttk.Frame(self.body, bootstyle="success", width=100)
        self.sidebar.pack(fill=ttk.Y, side=ttk.LEFT)
        self.body_canvas = ttk.Frame(self.body, bootstyle="dark")
        self.body_canvas.pack(fill=ttk.BOTH, expand=ttk.YES, side=ttk.LEFT)

        self.body.add(self.sidebar)
        self.body.add(self.body_canvas)

        self.init_body()

    def init_body(self):

        Work(self.body_canvas).build()

        draggable_frame = DraggableFrame(self.body_canvas, width=100, height=50, bootstyle='light')
        draggable_frame.place(x=50, y=50)

        draggable_frame2 = DraggableFrame(self.body_canvas, width=100, height=50, bootstyle='danger')
        draggable_frame2.place(x=200, y=50)


class Work(ttk.Canvas):
    """"""

    def __init__(self, master=None, **kwargs):
        super().__init__(master, **kwargs)

    def build(self) -> None:
        """"""
        bg = "#1F1F1F"
        self.configure(bg=bg, highlightthickness=0)
        self.pack(fill="both", expand=True, anchor="center")

        for x in range(-5, 2565, 16):
            self.create_line(x, -5, x, 1605, fill="grey")

        for y in range(-5, 1605, 16):
            self.create_line(-5, y, 2565, y, fill="grey")


if __name__ == '__main__':
    import time

    #from prophet import Prophet
    # import pandas
    # import matplotlib
    # import numpy


    try:
        print("导入DEA库：")
        data = np.array([[1, 2, 3]])
        df = pd.DataFrame(data, columns=['a', 'b', 'c'])
        print(data)
        print(df)
        import matplotlib.pyplot as plt
        plt.plot(data.flatten())
        plt.show()
    except Exception as e:
        print("error:", e.args)



    try:
        print("导入自定义包：")
        from myutil import Base
        print(Base.NAME)
        print("ok")
    except Exception as e:
        print("error")

    try:
        print("读取同路径下：")
        path = "./static/img.png"
        print(path)
        with open(path, "r") as f:
            print("ok")
    except Exception as e:
        print("error")


    try:
        print("读取exe目录：")
        import os
        path = os.path.join(os.path.dirname(__file__), 'static', 'pyflow.png')
        print(path)
        with open(path) as f:
            print("ok")
    except Exception as e:
        print(e.args)
        print("error")

    root = tk.Tk()
    root_width = 600
    root_height = 300
    root_x, root_y = 500, 200
    root.geometry(f"{root_width}x{root_height}+{root_x}+{root_y}")

    Body(root)
    root.mainloop()

